package coupon;

import models.BaseModel;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import models.weixin.WebUser;
import play.db.jpa.Model;

import javax.persistence.*;
import java.util.Date;
import java.util.List;

/**
 * Created by buhaoba on 2016/10/20.
 */
@Entity
@Table(name = "webuser_coupons")
public class WebUserCoupon extends BaseModel {

    /**
     *  用户
     */
    @JoinColumn(name = "web_user_id")
    @ManyToOne
    public WebUser webUser;

    /**
     *  代金券信息
     */
    @JoinColumn(name = "discount_coupon_id")
    @ManyToOne
    public DiscountCoupon discountCoupon;


    /**
     * 可用金额
     */
    public Double amount;

    /**
     * 逻辑删除状态
     */
    @Column(name = "deleted")
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;


    public WebUserCoupon() {
        super();
    }

    public WebUserCoupon(WebUser webUser , DiscountCoupon discountCoupon , Double amount) {
        this.webUser = webUser;
        this.discountCoupon = discountCoupon;
        this.amount = amount;
        this.deleted = DeletedStatus.UN_DELETED;
        this.createAt = new Date();
    }


    public static WebUserCoupon findByWebUser(WebUser webUser) {
        return WebUserCoupon.find("webUser = ? and deleted = ? order by id desc" , webUser , DeletedStatus.UN_DELETED).first();
    }

    public static List<WebUserCoupon> findAvailable() {
        return WebUserCoupon.find("deleted = ? and amount > ?" , DeletedStatus.UN_DELETED , 0.1d).fetch();
    }
}
